#include "widget_node_animation.h"
#include "ui_widget_node_animation.h"
#include "../AvatarLibrary.h"

WidgetNodeAnimation::WidgetNodeAnimation(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::WidgetNodeAnimation)
{
    ui->setupUi(this);
}

WidgetNodeAnimation::~WidgetNodeAnimation()
{
    delete ui;
}

void WidgetNodeAnimation::setupNode(const QString &name)
{
    ui->lineEditNode->setText(name);
    AvatarLibrary::avatar_register("__GetJointNames", handleJointNames, this);
    AvatarLibrary::avatar_register("__GetAnimationNames", handleAnimationNames, this);
    AvatarLibrary::avatar_command(QString("engine.execute('__GetJointNames', scene.handle('%1','GetJointList'))").arg(name));
    AvatarLibrary::avatar_command(QString("engine.execute('__GetAnimationNames', scene.handle('%1','GetAnimationList'))").arg(name));
}

/**
 * @brief 双击播放动画
 * @param item
 */
void WidgetNodeAnimation::on_listWidgetAnimation_itemDoubleClicked(QListWidgetItem *item)
{
    QString format = "scene.handle('%1','StartAnimation',{name='%2',loop=true,transition=1.0})";
    AvatarLibrary::avatar_command(format.arg(ui->lineEditNode->text(), item->text()));
}

/**
 * @brief 停止动画
 */
void WidgetNodeAnimation::on_pushButtonStop_clicked()
{
    QString format = "scene.handle('%1','StopAnimation')";
    AvatarLibrary::avatar_command(format.arg(ui->lineEditNode->text()));
}

/**
 * @brief 获取骨骼名称列表回调
 * @param count
 * @param nameList
 * @param form
 * @return
 */
int WidgetNodeAnimation::handleJointNames(int count, const char** nameList, void* form)
{
    QStringList jointList;
    for (int i = 0; i < count; i++) jointList.append("[" + QString::number(i) + "] " + nameList[i]);
    WidgetNodeAnimation* widget = static_cast<WidgetNodeAnimation*>(form);
    widget->ui->comboBoxJoint->clear();
    widget->ui->comboBoxJoint->addItems(jointList);
    widget->ui->comboBoxJoint->setCurrentIndex(-1);
    return 0;
}

/**
 * @brief 获取动画名称列表回调
 * @param count
 * @param nameList
 * @param form
 * @return
 */
int WidgetNodeAnimation::handleAnimationNames(int count, const char** nameList, void* form)
{
    WidgetNodeAnimation* widget = static_cast<WidgetNodeAnimation*>(form);
    widget->ui->listWidgetAnimation->clear();
    for (int i = 0; i < count; i++)
    {
        QListWidgetItem* item = new QListWidgetItem();
        item->setText(nameList[i]);
        item->setIcon(QIcon(":/resource/icon/scenetree/animation_normal.png"));
        item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
        widget->ui->listWidgetAnimation->addItem(item);
    }
    return 0;
}
